package jeju.daum.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import jeju.daum.model.Comment;
import jeju.daum.model.User;
import jeju.daum.service.CommentService;
import jeju.daum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes("user")      // Controller 메소드가 생성하는 Model 정보 중
								// "user" 이름을 가진 것이 있다면 그것을 세션이 저장한다.
public class LoginCommentController {

	@Autowired CommentService commentService;
	@Autowired UserService userService;
	private User user;
	
	@RequestMapping(value="/logincomment", method=RequestMethod.GET)
	public List<Comment> showLoginComment(){
        
		return commentService.getCommentList();
	}
	
	@RequestMapping(value="/logincomment", method=RequestMethod.POST)
	public List<Comment> showLoginComment(@RequestParam String id, Model model){
		
        // DB로부터 회원 데이터를 가져온다.
        // 여기서는 setter가 DB에서 가져온 데이터라고 생각하자.
        user = userService.getUser(id);
 
        // 이 user 오브젝트는 "user" 이름을 가진채로
        // Model에 추가되기 때문에 Session에 저장되게 된다.
        model.addAttribute("user", user);      
        
		return commentService.getCommentList();
	}
	
	@RequestMapping(value="/logincomment/save", method=RequestMethod.GET)
	public String showGetForm(@RequestParam String comment){
		Comment testComment = new Comment();
		testComment.setName(user.getName());
		testComment.setComment(comment);
		testComment.setRecommend(0);
		testComment.setOppose(0);
		testComment.setDate(getCurrentDateAndTime());
		commentService.saveComment(testComment);
		return "redirect:/logincomment";
	}
	
	@RequestMapping(value="logincomment/delete", method=RequestMethod.GET)
	public String deleteComment(@RequestParam int seq_num){
		commentService.deleteComment(seq_num);
		return "redirect:/logincomment";
	}
	
	@RequestMapping(value="logincomment/recommend", method=RequestMethod.GET)
	public String recommendComment(@RequestParam int seq_num){
		commentService.incrementRecommend(seq_num);
		return "redirect:/logincomment";
	}
	
	@RequestMapping(value="logincomment/oppose", method=RequestMethod.GET)
	public String opposeComment(@RequestParam int seq_num){
		commentService.incrementOppose(seq_num);
		return "redirect:/logincomment";
	}

	private String getCurrentDateAndTime() {
		SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd_HH:mm", Locale.KOREA);
		Date currentTime = new Date();
		String date = mSimpleDateFormat.format(currentTime);
		return date;
	}
}
